package com.ryl.yomall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.ryl.yomall.cart.client.CartFeignClient;
import com.ryl.yomall.model.cart.CartInfo;
import com.ryl.yomall.model.common.constant.RedisConst;
import com.ryl.yomall.model.common.result.Result;
import com.ryl.yomall.model.common.util.AuthContextHolder;
import com.ryl.yomall.model.order.OrderDetail;
import com.ryl.yomall.model.order.OrderInfo;
import com.ryl.yomall.model.user.UserAddress;
import com.ryl.yomall.order.service.OrderService;
import com.ryl.yomall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderService orderService;


    /**
     * 秒杀提交订单，秒杀订单不需要做前置判断，直接下单
     * @param orderInfo
     * @return
     */
    @PostMapping("inner/seckill/submitOrder")
    public Long submitOrder(@RequestBody OrderInfo orderInfo) {
        Long orderId = orderService.saveOrderInfo(orderInfo);
        return orderId;
    }

    /**
     * 确认订单
     * @param request
     * @return
     */
    @GetMapping("auth/trade")
    public Result<Map<String, Object>> trade(HttpServletRequest request) {
        // 获取到用户Id
        String userId = AuthContextHolder.getUserId(request);

        //获取用户地址
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);

        // 渲染送货清单
        // 先得到用户想要购买的商品！
        List<CartInfo> cartInfoList = cartFeignClient.findChecked ();
        // 声明一个集合来存储订单明细
        List<OrderDetail> detailArrayList = new ArrayList<> ();
        for (CartInfo cartInfo : cartInfoList) {
            OrderDetail orderDetail = new OrderDetail();

            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setOrderPrice(cartInfo.getCartPrice());

            // 添加到集合
            detailArrayList.add(orderDetail);
        }
        // 计算总金额
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailArrayList);
        orderInfo.sumTotalAmount();

        Map<String, Object> result = new HashMap<> ();
        result.put("userAddressList", userAddressList);
        result.put("detailArrayList", detailArrayList);
        // 保存总金额
        result.put("totalNum", detailArrayList.size());
        result.put("totalAmount", orderInfo.getTotalAmount());
//订单号或交易号
        // 1： UUID  2：雪花算法  保存Redis中  获取Redis取校验  删除
        // 3:  值 MD5   userId + skuId   MD5(371)  交易号 生成方式
        // 4:  userId+ 时间戳 + skuId
        // 防止二次提交
        String tradeNo = UUID.randomUUID().toString();

        redisTemplate.opsForValue().set( RedisConst.USER_TRADENO + userId,tradeNo);
        result.put("tradeNo",tradeNo);
        return Result.ok(result);
    }
    /**
     * 提交订单
     * @param orderInfo
     * @param request
     * @return
     */
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(String tradeNo,@RequestBody OrderInfo orderInfo,HttpServletRequest request) {
        // 获取到用户Id
        String userId = AuthContextHolder.getUserId(request);

        //1:检查是否二次提交   判断交易号是否正确或是是否存在
        System.out.println("交易号：" + tradeNo);
        Object o = redisTemplate.opsForValue ( ).get ( RedisConst.USER_TRADENO + userId );
        if(null != o){
            if(!o.equals (tradeNo  )){
                return Result.fail ().message ( "非法操作" );
            }else{
                redisTemplate.delete ( RedisConst.USER_TRADENO + userId );

            }
        }else{
            return Result.fail ().message ( "不能重复提交订单" );
        }
        //2:校验商品的库存是否还有货
        // 问仓库系统
        //无货： 购买数量8 大于库存数量 视认为无货    7
        //前端系统  消费系统  后台管理 平台系统  进销存 供货商系统  CMS内容管理系统
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            // 遇到没有货存  直接提示
            Boolean isHasStock = orderService.hasStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
            if(!isHasStock){
                return Result.fail().message(orderDetail.getSkuName() +  ":无货");
            }
        }
        // 验证通过，保存订单！
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderService.saveOrderInfo(orderInfo);
        return Result.ok(orderId);
    }
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){

       return orderService.getOrderInfo(orderId);
    }
    @GetMapping("/auth/{page}/{limit}")
     public Result getOrderPageList(@PathVariable Integer page ,@PathVariable Integer limit){
        Map orderPageList = orderService.getOrderPageList ( page ,limit );
        return Result.ok (orderPageList);
    }
    //仓库调用我们的订单微服务,要求进行拆单
    @PostMapping("/orderSplit")
    public String orderSplit(Long orderId,String wareSkuMap){
        //拆单
       List<OrderInfo> orderInfoList = orderService.orderSplit(orderId,wareSkuMap);
        //组装返回值
        List<Map> mapList = orderInfoList.stream().map(orderInfo -> {
            return orderService.initWareOrder(orderInfo);
        }).collect( Collectors.toList());
        return JSONObject.toJSONString(mapList);
    }

}
